<template>
  <transition name="fade">
    <div class="mask" v-show="showPicUpload">
      <div class="uploadtk" v-show="showPicUpload">
        <div class="dialog_head pr">
          <h2>裁剪背景</h2>
          <a href="javascript:void(0)" class="dialog_link close" @click="closeSelf">&times;</a>
        </div>
        <div class="wrapper">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :autoCrop="true"
            :info="true"
          ></vueCropper>
        </div>
        <Checkbox style="font-size:14px;text-align:center;" v-model="isUpdateAll">将该背景应用到所有页面</Checkbox>
        <div class="test-button">
          <label class="btn" for="uploads" style="margin-left:140px;">选择图片</label>
          <label class="btn"  @click="originPicUpload()" style="margin-left:140px;">原图上传</label>
          <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);"
                 accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg">
          <!--<a @click="startCrop" class="btn">开始裁剪</a>-->
          <!--<button @click="stopCrop"class="btn">stop</button>-->
          <a @click="down()" class="btn">确认上传</a>
          <a @click="clearCrop" class="btn cancel">取消裁剪</a>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
  import vueCropper from 'vue-cropper'
  import api from '../../api/index.js'
  export default {
    name: "uploadtk",
    props: ['showPicUpload'],
    data: function () {
      return {
        isUpdateAll: false,
        show: false,
        crap: false,
        previews: {},
        option: {
          img: '',
          size: 0.8,
          outputType: 'png'
        },
        downImg: '#'
      }
    },
    methods: {

      originPicUpload(){

        debugger
      },
      closeSelf() {
        this.$emit("close");
        this.option.img = '';
      },

      startCrop () {
        // start
        this.crap = true
        this.$refs.cropper.startCrop()
      },
      stopCrop () {
        //  stop
        this.crap = false
        this.$refs.cropper.stopCrop()
      },
      clearCrop () {
        // clear
        this.$refs.cropper.clearCrop()
      },
      // 实时预览函数
      // realTime (data) {
      // 	this.previews = data
      // },
      finish (type) {
        // 输出
        debugger

        var test = window.open('about:blank')
        test.document.body.innerHTML = '图片生成中..'
        if (type === 'blob') {
          this.$refs.cropper.getCropBlob((data) => {
            var test = window.open('')
            test.location.href = data
          })
        } else {
          this.$refs.cropper.getCropData((data) => {
            test.location.href = data
          })
        }
      },

      down (type) {
        this.$refs.cropper.getCropData((data) => {
          this.downImg = data
//          console.log(data)

          let param = new FormData()
          // param.append('file',data,new Date())
          var blob = this.dataURItoBlob(data);

          param.append('file', blob, new Date().getTime() + ".png");

//          console.log(param.get('file'));

          let config = {
            headers: {'Content-Type': 'multipart/form-data'}
          }
          this.$http.post(api.uploadPicType(1), param, config)
            .then(res => {
              // console.log(response.data);
              if (res.data.code == 200) {


                if (res.data.status) {

                  //上传成功\

                  // debugger

                  this.changeBg(res.data.file)


                } else {

                  this.$Message.error(res.data.msg);
                }


              } else {

                this.$Message.error('网络开小差啦~');
              }
            }).catch(error => { // 错误处理
            console.log(error)
            this.$Message.error('网络开小差啦~');
          })


        })
      },
      dataURItoBlob(dataURI) {
        var byteString = atob(dataURI.split(',')[1]);
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ab], {type: mimeString});
      },
      changeBg(file){

        //修改所有
        if (this.isUpdateAll) {


          var params = {};
          params.type = "bg";
          params.src = file.src;
          params.subType = 3;
          this.$store.dispatch('addPicOrBg', params);
        } else {

          var params = {};
          params.type = "bg";
          params.src = file.src;
          params.subType = 2;
          this.$store.dispatch('addPicOrBg', params);

        }

        this.closeSelf();

      },

      uploadImg (e) {
        //上传图片
        // this.option.img
        var file = e.target.files[0]
        if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
          // alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
          this.$Message.error('图片格式不正确~');
          return false
        }
        var reader = new FileReader()
        reader.onload = (e) => {
          this.option.img = e.target.result
        }
        reader.readAsDataURL(file)
        this.startCrop();
      }
    },
    components: {
      vueCropper
    },
  }
</script>

<style type="text/javascript" scoped>
  .mask {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, .5);
  }

  .uploadtk {
    position: fixed;
    width: 800px;
    height: 700px;
    top: 50%;
    left: 50%;
    margin-top: -350px;
    margin-left: -400px;
    padding: 10px 50px;
    background: #ffffff;
    box-shadow: -3px 0 5px 0 rgba(213, 213, 213, .35);
    z-index: 99999;
    font-size: 16px;
  }

  .uploadtk .dialog_head h2 {
    text-align: center;
    font-weight: normal;
    font-size: 18px;
    height: 50px;
    line-height: 50px;
    border-bottom: 1px solid #e6e6e6;
  }

  .uploadtk .dialog_head .close {
    position: absolute;
    font-size: 40px;
    height: 50px;
    line-height: 50px;
    right: 0;
    top: 0;
    color: #999;
  }

  .uploadtk .wrapper {
    height: 490px;
    margin: 25px auto 15px;
  }

  .uploadtk .test-button {
    overflow: hidden;
  }

  .uploadtk .test-button .btn {
    float: left;
    width: 100px;
    height: 35px;
    line-height: 35px;
    text-align: center;
    color: #fff;
    background: #1abd9b;
    margin: 15px 30px;
    border-radius: 5px;
  }

  .uploadtk .test-button .btn.cancel {
    border: 1px solid #999;
    color: #999;
    background: #fff;
  }

  .fade-transition {
    transition: all ease 0.3s;
    -webkit-transition: all ease 0.3s;
  }

  .fade-enter, .fade-leave {
    opacity: 0;
  }

  .fade-slow-transition {
    transition: all ease 0.7s;
    -webkit-transition: all ease 0.7s;
  }

  .fade-slow-enter, .fade-slow-leave {
    opacity: 0;
  }

  .fade-scale-transition {
    transition: all linear 0.2s;
    -webkit-transition: all linear 0.2s;
  }

  .fade-scale-enter, .fade-scale-leave {
    opacity: 0;
    transform: scale(1.08);
    -webkit-transform: scale(1.08);
  }

  .fromRight-transition {
    transition: all ease 10s;
    -webkit-transition: all ease 10s;
  }

  .fromRight-enter, .fromRight-leave {
    transform: translateX(100%);
    -webkit-transform: translateX(100%);
  }

  .fade1-enter-active, .fade1-leave-active {
    transition: opacity .5s
  }

  .fade1-enter, .fade1-leave-to .fade-leave-active in {
    opacity: 0
  }
</style>
